#include <stdio.h>
#include <pthread.h>
typedef struct
{
	pthread_mutex_t mutex;
	pthread_cond_t cond;
	int res;
	int is_wait;
}Data;
void* get_v(void*);
void* compare_v(void*);
int main(void)
{
	pthread_cond_t cond;
	pthread_mutex_t mutex;
	pthread_cond_init(&cond,NULL);
	pthread_mutex_init(&mutex,NULL);
	Data data = {mutex,cond,0,0};
	pthread_t thread1_id,thread2_id;
	if(pthread_create(&thread1_id,NULL,compare_v,(void*)&data) != 0)
	{
		printf("create thread1 error\n");
		return 1;
	}
	if(pthread_create(&thread2_id,NULL,get_v,(void*)&data) != 0)
	{
		printf("create thread2 error\n");
		return 1;
	}
	pthread_join(thread1_id,NULL);
	pthread_join(thread2_id,NULL);
	pthread_cond_destroy(&cond);
	pthread_mutex_destroy(&mutex);
	return 0;
}
// 获得输入和输出结果的线程函数
void* get_v(void* data)
{
	Data* d = (Data*)data;
	// 锁定数据，避免多个线程同时操作
	pthread_mutex_lock(&d->mutex);
	// 读取输入
	scanf("%d",&d->res);
	// 设置判断条件变量，使计算线程知道已经读取数据完毕
	d->is_wait = 1;
	// 等待计算线程计算完成
	pthread_cond_wait(&d->cond,&d->mutex);
	// pthread_cond_wait函数最后会将mutex再次锁住，所以这里要解锁
	pthread_mutex_unlock(&d->mutex);
	printf("res = %d",d->res);
	return (void*)NULL;
}
// 负责计算的线程函数
void* compare_v(void*data)
{
	Data* d = (Data*)data;
	// 先锁住，避免数据同时有多个线程操作
	pthread_mutex_lock(&d->mutex);
	// 判断输入线程是否已经正确读取输入
	while(d->is_wait == 0)
	{
		// 先解除锁定，给读取输入的线程机会去读取输入
		pthread_mutex_unlock(&d->mutex);
		usleep(0.1);
		// 再次锁定
		pthread_mutex_lock(&d->mutex);
	}
	// 读取数据线程成功读取，等待计算结果，下面进行计算
	int res = 0;
	for(int i = 0;i <= d->res;i++)
	{
		res += i;
	}
	d->res = res;
	// 先解除上面的锁定
	pthread_mutex_unlock(&d->mutex);
	// 通知输出线程输出数据
	pthread_cond_broadcast(&d->cond);
	return (void*)NULL;
}
